/*
	
*/

package net.sf.odinms.net.mina;

import net.sf.odinms.client.MapleClient;
import net.sf.odinms.net.MaplePacket;
import net.sf.odinms.net.channel.ChannelServer;
import net.sf.odinms.net.login.LoginServer;
import net.sf.odinms.tools.HexTool;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import net.sf.odinms.tools.WriteToFile;

public class MaplePacketEncoder implements ProtocolEncoder {
    private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MaplePacketEncoder.class);

    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);
        if (client != null ) {
            synchronized (client.getSendCrypto()) {
                byte[] input = ((MaplePacket) message).getBytes();
                if(client.isshowPacket()){
                if (input.length <= 30000) {
                    // 服务端反馈
                  //   WriteToFile re = new WriteToFile("D:\\Received.txt");
                  //   re.WriteFile("Received095:\r\n"+HexTool.toString(input)+"\r\nASCII:"+HexTool.toStringFromAscii(input));
                  //   log.info("服务端反馈:\r\n"+HexTool.toString(input)+"\r\nASCII:"+HexTool.toStringFromAscii(input));
                   //  re.CloseFile();
                   //  String s =HexTool.toString(input);
                   //  if(!s.substring(0, 5).equals("08 01")  && !s.substring(0, 5).equals("6F 00")) //忽略显示这个封包
                    // log.info(HexTool.toString(input));
                     //System.out.println("服务端反馈:\r\n"+HexTool.toString(input));
                }
                } else {
                  //log.info(HexTool.toString(new byte[]{input[0],input[1]})+" ...");
               
                }
                byte[] unencrypted = new byte[input.length];
                System.arraycopy(input, 0, unencrypted, 0, input.length);
                byte[] ret = new byte[unencrypted.length + 4];
                byte[] header = client.getSendCrypto().getPacketHeader(unencrypted.length);
                //MapleCustomEncryption.encryptData(unencrypted);
                client.getSendCrypto().crypt(unencrypted);
                System.arraycopy(header, 0, ret, 0, 4);
                System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);
                ByteBuffer out_buffer = ByteBuffer.wrap(ret);
                out.write(out_buffer);
           }
        } else {
            out.write(ByteBuffer.wrap(((MaplePacket) message).getBytes()));
        }
    }

    public void dispose(IoSession session) throws Exception {
    }
}